package tool

import (
	"fmt"
	"reflect"
	"strconv"
	"strings"
)

// 支持生成 周，时，分的 crontab 表达式
func CrontabExpr(week []int, hour int, minute int) string {
	weekStr := "*"
	if len(week) > 0 {
		weekStr = IntSliceToString(week, ",")
	}
	return fmt.Sprintf("%d %d * * %s", minute, hour, weekStr)
}

// []int 转 字符串
func IntSliceToString(arr []int, separator string) string {
	var strArr []string
	for _, i := range arr {
		strArr = append(strArr, strconv.Itoa(i))
	}
	return strings.Join(strArr, separator)
}

// 字符串 转 []int
func StringToIntSlice(str string, separator string) []int {
	str = strings.TrimSpace(str)
	strArr := strings.Split(str, separator)
	result := make([]int, 0, len(strArr))
	for _, s := range strArr {
		i, _ := strconv.Atoi(s)
		result = append(result, i)
	}
	return result
}

// array_diff
func IntSliceDiff(arr1, arr2 []int) []int {
	mb := make(map[int]struct{}, len(arr2))
	for _, i := range arr2 {
		mb[i] = struct{}{}
	}
	var diff []int
	for _, i := range arr1 {
		if _, ok := mb[i]; !ok {
			diff = append(diff, i)
		}
	}
	return diff
}

func IntSliceIntersect(arr1, arr2 []int) []int {
	mb := make(map[int]struct{}, len(arr2))
	for _, i := range arr2 {
		mb[i] = struct{}{}
	}
	var intersect []int
	for _, i := range arr1 {
		if _, ok := mb[i]; ok {
			intersect = append(intersect, i)
		}
	}
	return intersect
}

// IsNil 判断 interface 是否为空
func IsNil(i interface{}) bool {
	vi := reflect.ValueOf(i)
	if vi.Kind() == reflect.Ptr {
		return vi.IsNil()
	}
	return false
}
